public class Search {
    /**
     * 统计一个数字在排序数组中出现的次数。
     * @param nums
     * @param target
     * @return
     */
    public static int search(int[] nums, int target) {
        //先找到target,再统计个数
        if (nums.length==0)
            return 0;
        if (nums.length==1){
            if (target==nums[0])
                return 1;
            else
                return 0;
        }
        int low = 0;
        int high = nums.length-1;
        int flag = -1;
        while (low<=high){
            int mid = low +(high-low)/2;
            if (nums[mid]==target)
                flag = mid;
            if (nums[mid]<target){
                low =mid+1;
            }
            else {
                high = mid-1;
            }
        }

        if (flag==-1)
            return 0;
        else {
            int ans =1;
            int step=1;
            while (flag-step>0){
                if (nums[flag]==nums[flag-step]){
                    ans++;
                    step++;
                }else {
                    break;
                }
            }
            step = 1;
            while (flag+step<nums.length){
                if (nums[flag]==nums[flag+step]){
                    ans++;
                    step++;
                }else {
                    break;
                }
            }
            return ans;
        }


    }

    public static void main(String[] args) {
        int[] nums = {1,4};
        search(nums,4);
    }
}
